<template>
  <n-layout-sider
    :native-scrollbar="false"
    :collapsed-width="64"
    :width="200"
    :collapsed="collapsed"
    collapse-mode="width"
    show-trigger
    bordered
    inverted
    @collapse="collapsed = true"
    @expand="collapsed = false"
  >
    <n-menu
      :value="menuValue"
      :collapsed="collapsed"
      :collapsed-width="64"
      :collapsed-icon-size="22"
      :options="menuData"
      accordion
      inverted
    />
  </n-layout-sider>
</template>

<script lang="ts" setup>
import { computed, h, toRef } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import type { MenuOption } from 'naive-ui'
import { useStore } from '@/hooks/store'
import { deepTree } from '@/utils'

const { app, user } = useStore()
const route = useRoute()
const collapsed = toRef(app, 'collapsed')

const menuValue = computed(() => {
  const menus = user.menus.filter((item) => item.type !== 2)
  return menus.find((item) => item.router === route.path)?.id
})
const menuData = computed<MenuOption[]>(() => {
  // 1. 获取 menus
  const menus = user.menus
    .filter((item) => item.type !== 2)
    .map((item) => ({
      id: item.id,
      parentId: item.parentId,
      name: item.name,
      orderNum: item.orderNum,
      key: item.id,
      label: () => {
        if (item.router) {
          return h(RouterLink, { to: item.router }, { default: () => item.name })
        } else {
          return item.name
        }
      }
    }))

  return deepTree(menus)
})
</script>

<style lang="scss" scoped></style>
